package com.gohi.main.wxapi.util;

import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Formatter;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

import com.gohi.main.wxapi.vo.JsApi;

public class WxJsSign {
    public static void main(String[] args) {
        String jsapi_ticket = "bxLdikRXVbTPdHSM05e5u4RbEYQn7pNQMPrfzl8lJNb1foLDa3HIwI3BRMkQmSO_5F64VFa75uURcq6Uz7QHgA";
        String url = "http://omstest.vmall.com:23568/thirdparty/wechat/vcode/gotoshare?quantity=1&batchName=MATE7";
       JsApi ap = sign(jsapi_ticket, url);
       System.err.println(ap.getJsapi_ticket());
    };

	
	 public static JsApi sign(String jsapi_ticket, String url) {
	        Map<String, String> ret = new HashMap<String, String>();
	       String nonce_str = create_nonce_str();
	       String timestamp = create_timestamp();
	       // String nonce_str = "82693e11-b9bc-448e-892f-f5289f46cd0f";
	        //String timestamp = "1419835025";
	        String string1;
	        String signature = "";

	        //注意这里参数名必须全部小写，且必须有序
	        string1 = "jsapi_ticket=" + jsapi_ticket +
	                  "&noncestr=" + nonce_str +
	                  "&timestamp=" + timestamp +
	                  "&url=" + url;
	        //System.out.println(string1);

	        try
	        {
	            MessageDigest crypt = MessageDigest.getInstance("SHA-1");
	            crypt.reset();
	            crypt.update(string1.getBytes("UTF-8"));
	            signature = byteToHex(crypt.digest());
	        }
	        catch (NoSuchAlgorithmException e)
	        {
	            e.printStackTrace();
	        }
	        catch (UnsupportedEncodingException e)
	        {
	            e.printStackTrace();
	        }
	        JsApi p =new JsApi();
	        p.setUrl(url);
	        p.setNoncestr(nonce_str);
	        p.setTimestamp(timestamp);
	        p.setSignature(signature);
	        p.setJsapi_ticket(jsapi_ticket);
	        
	/*        ret.put("url", url);
	        ret.put("jsapi_ticket", jsapi_ticket);
	        ret.put("nonceStr", nonce_str);
	        ret.put("timestamp", timestamp);
	        ret.put("signature", signature);*/

	        return p;
	    }

	    private static String byteToHex(final byte[] hash) {
	        Formatter formatter = new Formatter();
	        for (byte b : hash)
	        {
	            formatter.format("%02x", b);
	        }
	        String result = formatter.toString();
	        formatter.close();
	        return result;
	    }

	    private static String create_nonce_str() {
	        return UUID.randomUUID().toString();
	    }

	    private static String create_timestamp() {
	        return Long.toString(System.currentTimeMillis() / 1000);
	    }
}
